package com.jingdianjichi.subject.service.impl;

import com.alibaba.fastjson.JSON;
import com.jingdianjichi.subject.config.RestClientConfig;
import com.jingdianjichi.subject.eneity.EmployeeBO;
import com.jingdianjichi.subject.infra.basic.entity.Employee;
import com.jingdianjichi.subject.service.ElasticsearchService;
import com.jingdianjichi.subject.service.EmployeeDomainService;
import com.jingdianjichi.subject.util.RestIndexClientUtil;
import lombok.SneakyThrows;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ElasticsearchServiceImpl implements ElasticsearchService {

    @Resource
    private RestIndexClientUtil restClientUtil;

    @Resource
    private EmployeeDomainService employeeDomainService;

    @Resource
    private RestHighLevelClient client;

    /**
     * 创建es索引库
     * @param indexName
     * @return
     */
    public CreateIndexResponse getEmployeeIndex(String indexName) {
        return restClientUtil.createIndex(indexName);
    }

    /**
     * 删除es索引库
     * @param indexName
     * @return
     */
    public void deleteEmployeeIndex(String indexName) {
        restClientUtil.deleteIndex(indexName);
    }

    /**
     * 根据es索引库创建文档
     * @param indexName
     * @return
     */
    @SneakyThrows
    public void addEmployeeIndexDocument(String indexName, String id) {
        if (indexName == null && indexName.trim().length() == 0) {
            throw new IllegalArgumentException("indexName不能为空");
        }
        EmployeeBO employeeBO = new EmployeeBO();
        employeeBO.setId(Integer.valueOf(id));
        EmployeeBO employeeBO1 = employeeDomainService.queryById(id);
        System.out.println(employeeBO1);
        IndexRequest request = new IndexRequest(indexName).id(id).source(JSON.toJSONString(employeeBO1), XContentType.JSON);
        IndexResponse index = client.index(request, RequestOptions.DEFAULT);
        System.out.println(index.toString());
    }

    /**
     * 根据id查询索引库文档
     * @param indexName
     * @return
     */
    @Override
    @SneakyThrows
    public void getEmployeeIndexDocument(String indexName, String id) {
        if (indexName == null && indexName.trim().length() == 0) {
            throw new IllegalArgumentException("indexName不能为空");
        }
        GetRequest request = new GetRequest(indexName).id(id);
        GetResponse documentFields = client.get(request, RequestOptions.DEFAULT);
        String sourceAsString = documentFields.getSourceAsString();
        EmployeeBO employeeBO = JSON.parseObject(sourceAsString, EmployeeBO.class);
        System.out.println(employeeBO);

    }

    /**
     *  根据id更新索引库文档
     * @param indexName
     * @param id
     */
    @Override
    @SneakyThrows
    public void updateEmployeeIndexDocument(String indexName, String id) {
        if (indexName == null && indexName.trim().length() == 0) {
            throw new IllegalArgumentException("indexName不能为空");
        }
        UpdateRequest updateRequest = new UpdateRequest(indexName, id);
        updateRequest.doc("username", "张三", "gender", "女");
        client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println("更新成功");
    }

    /**
     * 根据id删除索引库文档
     * @param indexName
     * @param id
     */
    @Override
    @SneakyThrows
    public void deleteEmployeeIndexDocument(String indexName, String id) {
        if (indexName == null && indexName.trim().length() == 0) {
            throw new IllegalArgumentException("indexName不能为空");
        }
        DeleteRequest deleteRequest = new DeleteRequest(indexName, id);
        client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println("删除成功");

    }

    /**
     * 批量添加索引库文档
     * @param indexName
     */
    @Override
    @SneakyThrows
    public void addEmployeeIndexDocumentBatch(String indexName) {
        EmployeeBO employeeBO = new EmployeeBO();
        employeeBO.setIsDeleted(1);
        List<EmployeeBO> employeeBOS = employeeDomainService.queryAllElement(employeeBO);
        System.out.println(employeeBOS);
        BulkRequest bulkRequest = new BulkRequest();
        employeeBOS.forEach(employeeBO1 -> {
            bulkRequest.add(new IndexRequest(indexName).id(employeeBO1.getId().toString()).source(JSON.toJSONString(employeeBO1), XContentType.JSON));
        });
        client.bulk(bulkRequest, RequestOptions.DEFAULT);
    }


    @Override
    @SneakyThrows
    public void getEmployeeIndexDocumentAll(String indexName) {
        if (indexName == null && indexName.trim().length() == 0) {
            throw new IllegalArgumentException("indexName不能为空");
        }
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.source().query(QueryBuilders.matchAllQuery());
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(search.toString());

    }


}
